#include						<QtWidgets/QMenu>
#include						"gui.h"
#include						"trayicon.h"

TrayIcon::TrayIcon(Gui &gui) : _gui(gui)
{
	_sticon = new QSystemTrayIcon(this);
	_manualconnect = new ManualConnect(0);
	_manualconnect->init();
	init();
}

TrayIcon::~TrayIcon()
{
}

void					TrayIcon::init()
{
	QAction				*quit = new QAction("Quit", this);
	QAction				*manualconnect = new QAction("Manual Connect", this);
	QIcon				icon("speaker.ico");
	QIcon				iexit("exit.ico");
	QIcon				isettings("setting.ico");
	QIcon				iserver("server.ico");


	_MainMenu = new QMenu();
	_Server = new QMenu("Server List");

	_MainMenu->addAction(manualconnect);
	_MainMenu->addSeparator();
	_MainMenu->addMenu(_Server);
	_MainMenu->addSeparator();
	_MainMenu->addAction(quit);
	
	_MainMenu->setStyleSheet("border: 3px solid lightblue;");
	_Server->setStyleSheet("border: 3px solid lightblue;");

	manualconnect->setIcon(isettings);

	quit->setIcon(iexit);
	_Server->setIcon(iserver);
	connect(quit, SIGNAL(triggered()), this, SLOT(close_window()));
	connect(manualconnect, SIGNAL(triggered()), this, SLOT(manual_connect()));

	_sticon->setContextMenu(_MainMenu);
	_sticon->setIcon(icon);
	_sticon->show();
	displayMessage("Unisound Client", "Unisound Client is running");
}

void					TrayIcon::close_window()
{
	QCoreApplication::quit();	
}

const ManualConnect		*TrayIcon::getDialog() const
{
	return _manualconnect;
}

void					TrayIcon::addServer(quint16 id, QString &serverName)
{
	_ServerList[id] = new ServerMenu(serverName, id, this);
	_Server->addMenu(_ServerList[id]);
	connect(_ServerList[id], SIGNAL(changeMode(quint16, bool)), this, SLOT(handleMode(quint16, bool)));
	connect(_ServerList[id], SIGNAL(config(quint16)), this, SLOT(handleConfig(quint16)));
}

void					TrayIcon::setName(QString &name, quint16 id)
{
	_ServerList[id]->changeName(name);
}

void					TrayIcon::removeServer(quint16 id)
{
	_ServerList[id]->deleteLater();
	_ServerList.erase(id);
}

void					TrayIcon::displayMessage(const std::string &titre, const std::string &message)
{
	_sticon->showMessage(QString(titre.c_str()), QString(message.c_str()));
}

void					TrayIcon::handleMode(quint16 id, bool mode)
{
	emit changeMode(id, mode);
}

void					TrayIcon::handleConfig(quint16 id)
{
	emit config(id);
}

void					TrayIcon::manual_connect()
{
	_manualconnect->setModal(true);
	_manualconnect->show();
}